package 环形链表;

import java.util.HashSet;
import java.util.Set;

/**
 * 环形链表
 * 给定一个链表，判断链表中是否有环
 * 如果链表中有某个节点，可以通过连续跟踪next指针，再次到达该节点，则链表中存在环
 */
public class Solution {
    public static void main(String[] args) {

        Node node5 = new Node(5, null);
        Node node4 = new Node(4, node5);
        Node node3 = new Node(3, node4);
        Node node2 = new Node(2, node3);
        Node node1 = new Node(1, node2);

        node5.next = node3;

        boolean res = hasCycle(node1);
        System.out.println("res = " + res);

        res = hasCycle2(node1);
        System.out.println("res = " + res);
    }

    /***
     * 双指针（快慢指针）
     * 时间复杂度O(N)
     */
    public static boolean hasCycle2(Node head) {

        if (head == null || head.next == null) {
            return false;
        }

        Node slow = head;
        Node quick = head.next;

        // 判断快慢指针相遇
        while (slow != quick) {

            if (quick == null || quick.next == null) {
                return false;
            }

            slow = slow.next;
            // 快指针，每次多跑一步
            quick = quick.next.next;
        }

        return true;

    }

    /**
     * 循环法
     * 时间复杂度O(N)
     * 空间复杂度O(N)
     */
    public static boolean hasCycle(Node head) {

        Set<Node> set = new HashSet<>();
        while (head != null) {
            if (set.contains(head)) {
                return true;
            }
            set.add(head);
            head = head.next;
        }
        return false;
    }

    public static class Node {
        Object v;

        Node next;

        public Node(Object v, Node next) {
            this.v = v;
            this.next = next;
        }
    }
}
